package org.mozhu.zufang.system.account.web.controller;

import org.apache.commons.lang3.StringUtils;
import org.mozhu.mboot.core.web.bind.annotation.ControllerDefaults;
import org.mozhu.mboot.core.web.controller.BaseCRUDController;
import org.mozhu.zufang.system.account.entity.Gender;
import org.mozhu.zufang.system.account.entity.User;
import org.mozhu.zufang.system.account.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;

@RequestMapping("/system/account/user")
@Controller
@ControllerDefaults(resourceIdentity = "system:user")
public class UserController extends BaseCRUDController<User, Long> {

    protected UserService getBaseService() {
        return (UserService) baseService;
    }

    @Override
    protected void setCommonData(Model model) {
        super.setCommonData(model);
        model.addAttribute("genders", Gender.values());
    }

    protected void beforeCreate(HttpServletRequest request, Model model, User user, BindingResult result, String backURL, RedirectAttributes redirectAttributes) {
        getBaseService().encryptPassword(user);
    }

    protected void beforeUpdate(HttpServletRequest request, Model model, User user, BindingResult result, String backURL, RedirectAttributes redirectAttributes) {
        if (StringUtils.isNotBlank(user.getPlainPassword())) {
            getBaseService().encryptPassword(user);
        }
    }
}
